(async ()=>{
    let key = ''//搜索关键字
    let sort = 0 //排序方式
    let brandIds = ''//品牌列表
    let pageNum = 1 //当前页
    let productsDom = document.querySelector('#products')
    let total = 0,rows = []

    //focus 获取焦点 blur失去焦点
    document.querySelector('#keyInput').addEventListener('blur',(event)=>{
        key = event.target.value
        productsDom.innerHTML = ''
        pageNum = 1
        getList()
    })

    //切换排序
    let sorts = document.querySelectorAll('.sort')
    let sortActive = sorts[0]
    for(let i = 0; i < sorts.length; i++){
        sorts[i].addEventListener('click',(event) => {
            sort = event.target.dataset.sorted
            productsDom.innerHTML = ''
            pageNum = 1
            getList()
            sortActive.className = 'sort'
            sortActive = event.target
            sortActive.className = 'sort active'
        })
    }

    //品牌
    let dialogContent = document.querySelector('#dialogContent')
    let brands = await (await fetch(`http://localhost:3001/brands`)).json()
    let brandActive = null
    for(let i = 0; i < brands.length; i ++){
        let brand = document.createElement('div')
        brand.className = 'brand'
        brand.innerHTML = `
            <img src="http://localhost:3001${brands[i].img}" />
            <div>${brands[i].name}</div>
        `
        //按品牌选择
        brand.addEventListener('click',event => {
            brandIds = brands[i]._id
            productsDom.innerHTML = ''
            pageNum = 1
            getList()
            document.querySelector('#dialog').style.display = 'none'

            //
            if(brandActive) brandActive.className = 'brand'
            brandActive = event.target
            brandActive.className = 'brand active'
        })

        dialogContent.appendChild(brand)
    }

    //打开弹框
    document.querySelector('#openDialog').addEventListener('click',event => {
        document.querySelector('#dialog').style.display = 'block'
    })
    //关闭弹框
    document.querySelector('#dialogCover').addEventListener('click',event => {
        document.querySelector('#dialog').style.display = 'none'
    })


    //获取数据总接口
    async function getList(){
        let res = await (await fetch(`http://localhost:3001/products?key=${key}&sorted=${sort}&brandIds=${brandIds}&pageNum=${pageNum}`)).json()
        total = res.total
        for(let i = 0; i < res.rows.length; i ++){
            rows.push(res.rows[i])
            let product = document.createElement('div')
            product.className = 'product'
            product.innerHTML = `
                <div>名字:${res.rows[i].productName}</div>
                <div>价格:¥${res.rows[i].salePrice / 100}<span style="color:#ccc;margin-left:16rem;text-decoration: line-through;">¥${res.rows[i].originalPrice / 100}</span></div>
                <div>销量:${res.rows[i].sales}</div>
            `
            productsDom.appendChild(product)
        }
    }
    getList()
})()